package com.anmi.transfer.task;

import com.anmi.alfred.entity.TransferCaseOperationResult;
import com.anmi.alfred.service.concreteservice.CaseOperationIndexService;
import com.anmi.transfer.service.TransferCaseOperationService;
import com.anmi.transfer.util.SpringContextUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Callable;

@Component
@Data
@Slf4j
public class MysqlTaskService implements Callable<Integer> {

  int from;
  int size;

  public MysqlTaskService() {}

  public MysqlTaskService(int limit, int offset) {
    this.from = limit;
    this.size = offset;
  }

  @Override
  public Integer call() {
    int index = 0;
    try {
      Thread.sleep(1000);
      TransferCaseOperationService transferCaseOperationService =
          SpringContextUtil.getBean(TransferCaseOperationService.class);
      CaseOperationIndexService caseOperationIndexService =
          SpringContextUtil.getBean(CaseOperationIndexService.class);
      List<TransferCaseOperationResult> list = transferCaseOperationService.selectPage(from, size);
      if (list != null && list.size() > 0) {
        long start = System.currentTimeMillis();
        log.info("线程{}正在处理从{}到{}的数据", Thread.currentThread().getName(), from, from + size);
        index = caseOperationIndexService.bulkIndex(TransferCaseOperationResult.ALIAS_NAME, list);
        log.info(
            "线程{}处理完成，共处理数据{}条，共使用时间{}ms",
            Thread.currentThread().getName(),
            index,
            (System.currentTimeMillis() - start));
      }
    } catch (Exception e) {
      log.error("线程{}处理失败,{}", Thread.currentThread().getName(), e.getMessage());
    }
    return index;
  }
}
